package cn.gson.crm.model.service;

import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.UserDao;
import cn.gson.crm.model.mapper.CenterMapper;
import cn.gson.crm.model.pojos.Employee;
import cn.gson.crm.model.pojos.User;
import cn.gson.crm.model.pojos.UserRole;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class CenterService {
    @Autowired
    CenterMapper centerMapper;

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    UserDao userDao;

    //个人中心查询
    public Map<String,Object> selectEmp(int ygId){
        User users = centerMapper.selectUser(ygId);
        Map<String,Object> map= new HashMap<>();
        map.put("user",users);
        //查询职位
        List<UserRole> userRoles = centerMapper.selectRole((int)users.getyId());
        map.put("roles",userRoles);
        return map;
    }

    //修改个人资料
    public void updateName(String position){
        JSONObject object = (JSONObject) JSONObject.parse(position);
        Employee emp = object.getObject("emp",Employee.class);
        //根据id查询出yId并且赋值
        Employee employee = employeeDao.findById(emp.getYgId()).get();
        emp.setUser(employee.getUser());
        employeeDao.save(emp);
        //修改User登录名
        Long yId = object.getLong("yId");
        User user = userDao.findById(Integer.parseInt(yId+"")).get();
        String yName = object.getString("yname");
        user.setyName(yName);
    }

    public void updateUser(User user){
        User user1 = userDao.findById(user.getyId()).get();
        user1.setyName(user.getyName());
        user1.setyAffress(user.getyAffress());
        user1.setyPhone(user.getyPhone());
        user1.setyProvince(user.getyProvince());
        user1.setyArea(user.getyArea());
        user1.setyAge(user.getyAge());
        user1.setyCity(user.getyCity());
        user1.setySex(user.getySex());
        userDao.save(user1);
    }

    //修改密码
    public void updatePwd(String position){
        JSONObject object = (JSONObject)JSONObject.parse(position);
        long yId = object.getLong("yid");
        String pwd = object.getString("pwd");
        User user = userDao.findById(Integer.parseInt(yId+"")).get();
        user.setyPwd(pwd);
        userDao.save(user);
    }

    //更换头像
    public void updateSrc(int yId,String src){
        User user = userDao.findById( yId).get();
        user.setySrc(src);
        userDao.save(user);
    }
}
